const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const typescript = require('rollup-plugin-typescript');
const serve = require('rollup-plugin-serve');
const livereload = require('rollup-plugin-livereload');
const path = require('path');
const fs = require('fs');
const { execSync } = require('child_process');

const packagesDir = path.resolve(__dirname, '../../packages');

// 获取命令行参数
const argv = process.argv.slice(2);
const isWatchMode = argv.includes('-w') || argv.includes('--watch');

// 获取所有模块的路径
const packages = fs.readdirSync(packagesDir).filter(pkg => {
  const stat = fs.statSync(path.join(packagesDir, pkg));
  return stat.isDirectory() && pkg !== 'example';
});

// 构建每个模块的输入和输出配置
const buildPackageConfig = (pkg) => ({
  input: path.join(packagesDir, pkg, 'src', 'index.ts'),
  output: [
    {
      file: path.join(packagesDir, pkg, 'dist', 'index.umd.js'),
      format: 'umd',
      name: pkg.charAt(0).toUpperCase() + pkg.slice(1),
    },
    {
      file: path.join(packagesDir, pkg, 'dist', 'index.esm.js'),
      format: 'esm',
    },
    {
      file: path.join(packagesDir, pkg, 'dist', 'index.cjs.js'),
      format: 'cjs',
    },
  ],
  plugins: [
    resolve(),
    commonjs(),
    typescript(),
  ],
});

// 构建 example 页面的打包配置
const buildExampleConfig = () => ({
  input: path.join(packagesDir, 'example', 'index.ts'),
  output: {
    file: path.join(packagesDir, 'example', 'dist', 'bundle.js'),
    format: 'iife',
    sourcemap: true,
  },
  plugins: [
    resolve(),
    commonjs(),
    typescript(),
    serve({
      contentBase: [path.join(packagesDir, 'example')],
      port: 3000,
    }),
    livereload({
      watch: path.join(packagesDir, 'example', 'dist'),
    }),
  ],
});

// 根据模式选择配置
const inputConfigs = isWatchMode
  ? [buildExampleConfig()]
  : packages.map(buildPackageConfig);

// 在所有模块打包完成后安装依赖
inputConfigs.forEach(config => {
  config.plugins.push({
    name: 'pnpm-install',
    buildEnd() {
      console.log(`Running pnpm install for ${config.input}`);
      execSync('pnpm install', { cwd: path.dirname(config.input) });
    },
  });
});

// 导出所有配置
module.exports = inputConfigs;